package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dto.UserDto;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
@Service
public class ILoginServiceImp implements ILoginService {

    @Autowired
    MemberMapper memberMapper;
    @Autowired
    UserConverterMapper userConverterMapper;

    @Override
    public UserLoginResponse login(UserLoginRequest request) {
        //密码加密
        String pass = DigestUtils.md5DigestAsHex(request.getUserPwd().getBytes());
        //查询数据库
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",request.getUserName())
                .andEqualTo("password",pass);
        List<Member> members = memberMapper.selectByExample(example);
        if (members.size() != 1) {
            return null;
        }
        UserLoginResponse converter = userConverterMapper.converter(members.get(0));
        //判断是否激活
        if ("N".equals(members.get(0).getIsVerified())) {
            return converter;
        }
        UserDto userDto = new UserDto();
        userDto.setUid(converter.getId());
        userDto.setUsername(converter.getUsername());
        //加密Token
        String string = JSON.toJSON(userDto).toString();
        String s = JwtTokenUtils.builder().msg(string).build().creatJwtToken();
        converter.setToken(s);
        return converter;
    }


    @Override
    public UserDto verificationLogin(Long uid) {
        Member member = memberMapper.selectByPrimaryKey(uid);
        UserDto userDto = new UserDto();
        userDto.setUid(member.getId());
        userDto.setUsername(member.getUsername());
        return userDto;
//    public UserLoginResponse selectById(Long uid) {
//
//       UserLoginResponse response= memberMapper.selectById(uid);
//        return response;
    }

}
